#!/usr/bin/python3.7

# @Version: V1.0
# @Author: wevsmy
# @License: Apache Licence
# @Contact: wevsmy@gmail.com
# @Site: https://blog.weii.ink
# @Software: PyCharm
# @File: solution-python.py
# @Time: 2020/4/17 下午2:


from typing import List


class ListNode:
    def __init__(self, val):
        if isinstance(val, int):
            self.val = val
            self.next = None

        elif isinstance(val, list):
            self.val = val[0]
            self.next = None
            cur = self
            for i in val[1:]:
                cur.next = ListNode(i)
                cur = cur.next

    def gatherAttrs(self):
        return ", ".join("{}: {}".format(k, getattr(self, k)) for k in self.__dict__.keys())

    def __str__(self):
        return self.__class__.__name__ + " {" + "{}".format(self.gatherAttrs()) + "}"


class Solution:
    # 01
    # https://leetcode-cn.com/problems/two-sum/
    # target - v = 0
    # 在字典中判断存在与否
    # 利用字典k存在重新赋值v
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        tmpDict = {}
        for k, v in enumerate(nums):
            if tmpDict.get(target - v) is not None:
                return [tmpDict.get(target - v), k]
            tmpDict[v] = k

    # 02
    # https://leetcode-cn.com/problems/add-two-numbers/
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        carry = flag = 0  # 进位  第一次的标志位
        while l1 or l2:
            x = l1.val if l1 else 0  # 取出每个节点
            y = l2.val if l2 else 0
            sums = (x + y + carry) % 10  # 取余
            carry = 0 if sums else (x + y + carry) // 10
            if not flag:
                flag = 1
                newListNode = ListNode(sums)  # 实例化一个新的链表
                node = newListNode
            else:
                node.next = ListNode(sums)
                node = node.next
            if l1: l1 = l1.next  # 跳出循环条件
            if l2: l2 = l2.next
        if carry: newListNode.next = ListNode(carry)
        return newListNode


if __name__ == '__main__':
    s = Solution()
    # print(s.twoSum([2, 7, 11, 15], 9))
    # print(s.addTwoNumbers(ListNode([2, 4, 3]), ListNode([5, 6, 4])))
    # print(s.addTwoNumbers(ListNode([5]), ListNode([5])))
    print(s.addTwoNumbers(ListNode([9]), ListNode([9])))
    pass
